#import "CheckoutController.h"

@implementation NewTextView

static CGFloat leftMargin = 5;

- (CGRect)textRectForBounds:(CGRect)bounds {
    bounds.origin.x += leftMargin;

    return bounds;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    bounds.origin.x += leftMargin;

    return bounds;
}
@end

@interface CheckoutController ()<UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property(strong, nonatomic) UIImagePickerController* imagePickerController;
@property(strong, nonatomic) UIImageView* imagePickerControllerView;

@property(strong, nonatomic) UIViewController* su;
@property(strong, nonatomic) DiscoverController* discover;

@property(strong, nonatomic) UILabel* timeLabel;
@property(strong, nonatomic) NewTextField* time;
@property(strong, nonatomic) UILabel* areaLabel;
@property(strong, nonatomic) NewTextField* area;
@property(strong, nonatomic) UILabel* placeLabel;
@property(strong, nonatomic) NewTextField* place;
@property(strong, nonatomic) UILabel* feelLabel;
@property(strong, nonatomic) NewTextView* feel;
@property(strong, nonatomic) UILabel* photoLabel;
@property(strong, nonatomic) UICollectionView* photos;
@property(strong, nonatomic) NSMutableArray* photodata;
@property(strong, nonatomic) UIImage* defaultImage;

@property(strong, nonatomic) UIAlertController* alert;
@end

@implementation CheckoutController

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imagePickerController=[[UIImagePickerController alloc]init];
    self.imagePickerController.delegate=self;
    self.imagePickerControllerView=[[UIImageView alloc]initWithFrame:CGRectMake(40, 100, 200, 200)];
    self.imagePickerControllerView.contentMode=UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.imagePickerControllerView];
    
    self.photodata = [[NSMutableArray alloc] init];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 200, 30)];
    self.timeLabel.text = @"时间：";
    self.timeLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.timeLabel];
    
    self.time = [[NewTextField alloc] initWithFrame:CGRectMake(120, 100, 250, 30)];
    self.time.layer.borderColor = [UIColor systemRedColor].CGColor;
    self.time.layer.borderWidth = 1;
    [self.view addSubview:self.time];
    
    self.areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 160, 200, 30)];
    self.areaLabel.text = @"地点：";
    self.areaLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.areaLabel];
    
    self.area = [[NewTextField alloc] initWithFrame:CGRectMake(120, 160, 250, 30)];
    self.area.layer.borderColor = [UIColor systemRedColor].CGColor;
    self.area.layer.borderWidth = 1;
    [self.view addSubview:self.area];
    
    self.placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 220, 200, 30)];
    self.placeLabel.text = @"景点名称：";
    self.placeLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.placeLabel];
    
    self.place = [[NewTextField alloc] initWithFrame:CGRectMake(120, 220, 250, 30)];
    self.place.layer.borderColor = [UIColor systemRedColor].CGColor;
    self.place.layer.borderWidth = 1;
    [self.view addSubview:self.place];
    
    self.feelLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 280, 200, 30)];
    self.feelLabel.text = @"个人心得：";
    self.feelLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.feelLabel];
    
    self.feel = [[NewTextView alloc] initWithFrame:CGRectMake(120, 280, 250, 120)];
    self.feel.layer.borderColor = [UIColor systemRedColor].CGColor;
    self.feel.layer.borderWidth = 1;
    self.feel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.feel];
    
    self.photoLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 420, 200, 30)];
    self.photoLabel.text = @"配图：";
    self.photoLabel.font = [UIFont systemFontOfSize:17];
    [self.view addSubview:self.photoLabel];
    
    NSString* image = @"plus.png";
    self.defaultImage = [UIImage imageNamed:image inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    
    UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [but addTarget:self action:@selector(submitCheckout) forControlEvents:UIControlEventTouchUpInside];
    [but setFrame:CGRectMake(100, 700, 215, 40)];
    [but setTitle:@"提交" forState:UIControlStateNormal];
    [but setExclusiveTouch:YES];
    but.layer.borderWidth = 1.0;
    but.layer.borderColor = [[UIColor redColor] CGColor];
    [self.view addSubview:but];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tabBarController.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateSelected];
    
    [self.su setTitle:@"添加打卡"];
    if(self.photos != nil) {
        [self.photos removeFromSuperview];
    }
    
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(345, 100);
    self.photos = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 450, 345, 235) collectionViewLayout:layout];
    self.photos.backgroundColor = [UIColor whiteColor];

    [self.photos setDataSource:self];
    [self.photos setDelegate:self];
    [self.photos registerClass:[PhotoCell class] forCellWithReuseIdentifier:@"checkout"];
    
    UIGestureRecognizer* touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editEnding)];
    [self.photos addGestureRecognizer:touch];
    self.photos.userInteractionEnabled = true;
    
    [self.view addSubview:self.photos];
}

- (void) editEnding {
    [self.view endEditing:YES];
}


- (CheckoutController*) initWithSuper:(UIViewController* ) su {
    self = [self init];
    self.su = su;
    return self;
}

- (void) setDiscoverController:(DiscoverController*) dc {
    self.discover = dc;
}

- (void) submitCheckout {
    Check* check = [Check init:self.time.text at:self.area.text where:self.place.text with:self.feel.text photos:self.photodata];
    [self.discover addCheck:check];
    [self showText:@"打卡成功"];
    [self clear];
}

- (void) showText:(NSString*)text {
    self.alert = [UIAlertController alertControllerWithTitle:@"提示" message:text preferredStyle:UIAlertControllerStyleAlert];
    [self.alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:self.alert animated:YES completion:nil];
    [self performSelector:@selector(dismissAlertView:) withObject:self.alert afterDelay:1.5];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(dismissAlertView:)
                                   userInfo:nil
                                    repeats:NO];
}

- (void)dismissAlertView:(NSTimer*)timer {
    [self.alert dismissViewControllerAnimated:YES completion:nil];
    self.tabBarController.selectedViewController = [self.tabBarController.viewControllers objectAtIndex:0];
}

- (void) clear {
    self.time.text = @"";
    self.area.text = @"";
    self.place.text = @"";
    self.feel.text = @"";
    self.photodata = [[NSMutableArray alloc] init];
    [self viewWillAppear:YES];
}

- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    
    PhotoCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"checkout" forIndexPath:indexPath];
    NSInteger count = self.photodata.count;
    NSInteger from = row * 3;
    
    UIImage* image1 = nil;
    UIImage* image2 = nil;
    UIImage* image3 = nil;
    BOOL defaultUsed = NO;
    NSInteger defaultIndex = 0;
    
    
    if(count <= from) {
        defaultUsed = YES;
        defaultIndex = 1;
        image1 = self.defaultImage;
    } else {
        image1 = self.photodata[from];
    }
    
    from ++;
    
    if(count <= from) {
        if(defaultUsed == NO) {
            defaultUsed = YES;
            defaultIndex = 2;
            image2 = self.defaultImage;
        }
    } else {
        image2 = self.photodata[from];
    }
    
    from ++;
    
    if(count <= from) {
        if(defaultUsed == NO) {
            defaultUsed = YES;
            defaultIndex = 3;
            image3 = self.defaultImage;
        }
    } else {
        image3 = self.photodata[from];
    }
    [cell setController:self];
    [cell setProperty:image1 with:image2 with:image3 canClick:defaultIndex];
    
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger line;
    
    if(self.photodata.count == 0) {
        line = 1;
    } else {
        if(self.photodata.count % 3 == 0) {
            line = (self.photodata.count) / 3 + 1;
        } else {
            line = self.photodata.count / 3 + 1;
        }
    }
    
    return line;
}

- (IBAction)openPickerPickController {
    [self presentViewController:self.imagePickerController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage * image=[info objectForKey:UIImagePickerControllerOriginalImage];
    [self addImage:image];
}

- (void) addImage: (UIImage*) image {
    [self.photodata addObject:image];
    [self viewWillAppear: YES];
}

@end
